package com.syezon.wifikey.utils;

import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.Context;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Build;
import android.util.Log;

import java.lang.reflect.Method;

public class LowVersionPermissionUtils {

    public static boolean hasLocationPermission() {
        try {
            LocationManager lm = (LocationManager) Utils.getApp().getSystemService(Context.LOCATION_SERVICE);
            // 无用操作
            lm.getAllProviders();
        } catch (Exception e) {
            return false;
        }
        return checkOp(Utils.getApp(), 1);
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private static boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= Build.VERSION_CODES.KITKAT) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
                Class clazz = AppOpsManager.class;
                Method method = clazz.getDeclaredMethod("checkOp", int.class, int.class, String.class);
                int result = (int) method.invoke(manager, op, Binder.getCallingUid(), context.getPackageName());
                Log.e("permission", "op : " + op + " result : " + result);
                return AppOpsManager.MODE_ALLOWED == result;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return true;
        }
        return false;
    }

}
